<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <title>try...catch 与 throw 语句</title>
    <style>
        .fieldname,
        .submit {
            text-align: right;
        }
    </style>
</head>
<body>
<form name="login">
    <table>
        <tr>
            <td class="fieldname">Username:</td>
            <td><label for="username"><input id="username" type="text"></label></td>
            <td><a id="username-availability" href="#">Check Availability</a></td>
        </tr>
        <tr>
            <td class="fieldname">Email:</td>
            <td><label for="email"><input id="email" type="email"></label></td>
            <td><a id="email-availability" href="#">Check Availability</a></td>
        </tr>
        <tr>
            <td class="fieldname">Password:</td>
            <td><label for="password"><input id="password" type="password"></label></td>
        </tr>
        <tr>
            <td class="fieldname">Verify Password:</td>
            <td><label for="verify-passowrd"><input id="verify-passowrd" type="password"></label></td>
        </tr>
        <tr>
            <td class="submit" colspan="2"><label for="submit"><input id="submit" type="submit"></label></td>
            <td></td>
        </tr>
    </table>
</form>
<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>
<script>
    function checkUsername(e) {
        e.preventDefault();
        var username = $('#username').val();

        try {
            if (!username) {
                throw {message: 'Please enter a user name to check!'};
            }
            var parms = {username: username};
            $.getJSON('form-validator.php', parms).done(handleResponse);
        } catch (e) {
            alert(e.message);
        }

    }

    function checkEmail(e) {
        e.preventDefault();
        var email = $('#email').val();
        try {
            if (!email) {
                throw {message: 'Please enter an email address to check!'};
            }
            var parms = {email: email};
            $.getJSON('form-validator.php', parms).done(handleResponse);
        } catch (e) {
            alert(e.message);
        }
    }

    function handleResponse(e) {
        if (e.available) {
            alert(response.searchTerm + ' is available!');
        } else {
            alert('We\'re sorry, but ' + response.searchTerm + ' is not available.');
        }
    }

    $('#username-availability').on('click', checkUsername);
    $('#email-availability').on('click', checkEmail);
</script>
</body>
</html>